import { Directive } from 'vue'

function getInput(el: any) {
	let inputEle
	if (el.tagName !== 'INPUT') {
		inputEle = el.querySelector('input')
	} else {
		inputEle = el
	}
	return inputEle
}
function clearTrim(inputEle: any) {
	inputEle.value = inputEle.value.trim() //这里会存在input框中的内容改了，但是v-model绑定的值没有被更改到
}
export const trim: Directive = {
	mounted(el) {
		let inputEle = getInput(el)
		const blurHandler = function () {
			clearTrim(inputEle)
		}
		const enterHandler = function (e: { keyCode: number }) {
			if (e.keyCode === 13) {
				clearTrim(inputEle)
			}
		}
		inputEle._blurHandler = blurHandler
		inputEle._enterHandler = enterHandler
		inputEle.addEventListener('blur', blurHandler)
		inputEle.addEventListener('keydown', enterHandler)
	},
	unmounted(el) {
		let inputEle = getInput(el)
		inputEle.removeEventListener('blur', inputEle._blurHandler)
		inputEle.removeEventListener('keydown', inputEle._enterHandler)
	}
}
